import config from '@/config/config.js'
import inisENV from '@/config/config.js'
import {
	inisHelper
} from '@/utils/helper.js'
import Request from '@/utils/luch-request/index.js'
import {
	router
} from '../router/router'
import store from '../store'

const http = new Request()

// 全局配置
http.setConfig((config) => {
	config.baseURL = inisHelper.customProcessApi(inisENV.api)
	config.header = {
		'Content-Type': 'application/json',
	}
	config.timeout = 60 * 1000
	return config
})
// 刷新请求
const refresh = new Request()
refresh.setConfig((config) => {
	/* 设置全局配置 */
	config.baseURL = inisHelper.customProcessApi(inisENV.api)
	config.header = {
		'Content-Type': 'application/json',

	}
	config.timeout = 60 * 1000
	return config
})

// 请求后刷新
const againHttp = new Request()
againHttp.interceptors.request.use(config => {
	config.header['Authorization'] = uni.getStorageSync('token')
	return config
}, error => {
	return Promise.reject(error)
})
// 请求拦截
// 所有的网络请求都会先走这个方法
http.interceptors.request.use((config) => {
	config.header = {
		...config.header,
	}
	const token = uni.getStorageSync('token')
	//如果本地不存在token
	if (!token && store.state.hasLogin) {
		router.push({
			path: '/pages/user/login',
		})
	}
	//如果请求为get且token为默认token则不拦截
	// if (config.method == 'GET') config.params.token = inisENV.token
	//如果本地存在token
	if (token) {
		config.header['token'] = uni.getStorageSync('token');
	}
	return config
}, (config) => {
	return Promise.reject(config)
})
// 响应拦截
//   所有的网络请求返回数据之后都会先执行这个方法
http.interceptors.response.use(async (response) => {
	const token = uni.getStorageSync('token')
	const nowtime = Math.round(Date.now() / 1000).toString();
	if (response.data.code === 403 || response.data.code === 402) {
		this.$Router.push({
			path: '/pages/user/login'
		})
		uni.showToast({
			icon: 'none',
			title: '登录失效请重新登录'
		})
	}
	return response
}, error => {
	return Promise.reject(error)
})

export default http
export {
	http
}